// Every two seconds the Client uploads a new timestamp with its coorresponding ID#
package threads;

import java.awt.Color;
import java.sql.ResultSet;
import robot.DBComm;

/**
 * This thread is responsible for continuously updating a timestamp
 * in the database in order to not time out.  This is done so that
 * users are given the opportunity to access the physical robots in a queue
 * such that only 1 user may operate the robots at a time.  Utilizes a
 * first in first out (FIFO) prioritization.
 *
 * @author      Gabriel Loewen
 * @author      James Weston
 */
public class QueueClient implements Runnable {

    public static int position = 0;
    public static String id = "";
    public static boolean run = false;

    /**
     * Default Constructor
     */
    public QueueClient() {
    }

    /**
     * Stops the threads execution
     */
    public void stop() {
        run = false;
    }

    /**
     * Creates a unique ID and inserts that id into the database along with
     * a time stamp.  Then, every 2 seconds it updates that timestamp with the
     * current time.  If other users have have timed out or have exited the
     * program the position in the queue is recalculated.
     */
    public void run() {
        id = DBComm.buildID();
        run = true;
        boolean started = false;
        long start = 0, stop = 0;
        while (run) {
            try {
                DBComm.updateID();
                gui.Client.jbtID.setText("Position in queue: " + position);
                if (position == 1) {
                    gui.Client.jbtID.setForeground(Color.green);
                    //starts a timer
                    if (!started) {
                        start = System.currentTimeMillis();
                        started = true;
                    }
                    stop = System.currentTimeMillis();
                    //15 minute time limit on position 1
                    if ((stop - start) > 900000) {
                        //puts user back into queue
                        id = DBComm.buildID();
                        started = false;
                    }
                } else {
                    gui.Client.jbtID.setForeground(Color.red);
                }
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
            }
        }
    }
}
